<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use App\Logic\ImLogic;
use App\Logic\LiveLogic;
use App\Logic\MatchLogic;
use App\Logic\UserLogic;
use App\Model\ApplyAnchor;
use App\Model\ApplyExpert;
use App\Model\Live;
use App\Model\User;
use App\Model\UserModelAnchor;
use App\Model\UserModelAssist;
use App\Model\UserModelExpert;
use App\Service\LiveService;
use App\Task\CalcRedbillRankingTask;
use App\Task\SyncArticleTask;
use App\Task\TestAutoReleaseScheme;
use App\Task\VirtualAnchorLiveTask;
use App\Utils\Enum\LiveEnum;
use App\Utils\Enum\UserEnum;
use App\Utils\LiveApi;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Context\Context;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\AutoController;
use PhpParser\Node\Expr\Print_;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use function Hyperf\Support\env;
use function Hyperf\Support\make;

#[AutoController]
class IndexController extends AbstractController
{
    public function test(): ResponseInterface
    {
        return $this->apiReturn(200, 'succ', ['time' => date('Y-m-d H:i:s')]);
    }

    public function testExpertCalc(): void
    {
        $this->container->get(CalcRedbillRankingTask::class)->execute();
    }

    public function testApi()
    {
        $matchId = 'j3746u0dgo3fgqo';
        $api = $this->container->get(LiveApi::class);
        $res = $api->getMatchInfo('j3746u0dgo3fgqo');
        print_r($res);
    }

    /**
     * 修复缺失IM ID的用户
     * @return ResponseInterface
     */
    public function testRepairImId(): ResponseInterface
    {
        $succ = 0;
        $users = User::query()->where('im_id', 0)->get(['id']);
        if (!empty($users)) {
            foreach ($users as $user) {
                $imID = ImLogic::createImID();
                User::query()->where('id', $user['id'])->update([
                    'im_id' => $imID,
                ]);
                $succ++;
            }
        }
        return $this->apiReturn(200, sprintf('成功修复%d个用户', $succ));
    }

    /**
     * 测试执行自动发布方案任务
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function testVirtualReleaseProject(): ResponseInterface
    {
        $this->container->get(TestAutoReleaseScheme::class)->execute();
        return $this->apiReturn(200, '自动发布方案任务执行完成');
    }

    public function testVirtualAnchorTask()
    {
        $this->container->get(VirtualAnchorLiveTask::class)->execute();
        return $this->apiReturn(200, 'succ');
    }

    /**
     * 审核入驻
     * @return ResponseInterface
     */
    public function testAuditSettled()
    {
        $list = ApplyAnchor::query()->where('audit_status', 0)->get()->toArray();
        $count = ['anchor' => 0, 'expert' => 0];
        if (!empty($list)) {
            $assistantUsers = UserModelAssist::query()->get()->toArray();
            if (!empty($assistantUsers)) {
                foreach ($list as $r) {
                    ApplyAnchor::query()->where('id', $r['id'])->update([
                        'audit_status' => 1,
                        'audit_time' => time()
                    ]);
                    User::query()->where('id', $r['userid'])->update([
                        'role_id' => UserEnum::USER_TYPE_ANCHOR
                    ]);
                    UserModelAnchor::create([
                        'userid' => $r['userid'],
                        'column_id' => $r['live_column_id'],
                        'assistant_userid' => $assistantUsers[array_rand($assistantUsers)]['userid'], //随机分配助理
                    ]);
                    $count['anchor']++;
                }
            }
        }

        $expertList = ApplyExpert::query()->where('audit_status', 0)->get()->toArray();
        if (!empty($expertList)) {
            foreach ($expertList as $r) {
                ApplyAnchor::query()->where('id', $r['id'])->update([
                    'audit_status' => 1,
                    'audit_time' => time()
                ]);
                User::query()->where('id', $r['userid'])->update([
                    'role_id' => UserEnum::USER_TYPE_EXPERT
                ]);
                UserModelExpert::create([
                    'userid' => $r['userid'],
                    'column_id' => $r['live_column_id'],
                    'expert_id' => 1,
                    'expert_desc' => '民间高手',
                ]);
                $count['expert']++;
            }
        }
        return $this->apiReturn(200, sprintf('成功审核 %d 条主播入组，%d 条专家入驻', $count['anchor'], $count['expert']));
    }

    /**
     * 创建虚拟直播间
     * @return ResponseInterface
     */
    public function testCreateVirtualAnchor(): ResponseInterface
    {
        $num = 15;
        $succ = 0;
        for ($i = 1; $i <= $num; $i++) {
            $nickName = '原声直播' . str_pad((string)$i, 2, '0', STR_PAD_LEFT);
            if (User::query()->where('nickname', $nickName)->exists()) {
                continue;
            }
            Db::beginTransaction();
            try {
                $username = 'u' . random(10);
                $user = UserLogic::register([
                    'username' => $username,
                    'nickname' => $nickName,
                    'mobile' => '',
                    'email' => 'live-' . $username . '@live.91kuaixiu.com',
                    'avatar' => 'upload/5kH2ppsRSYyLjlo9nEYAHQ.jpg',
                    'roleId' => UserEnum::USER_TYPE_ANCHOR,
                    'isVirtual' => 1,
                    'password' => md5($username),
                ]);
                $roomId = LiveLogic::createRoomId();
                $anchor = UserModelAnchor::create([
                    'userid' => $user['id'],
                    'room_id' => $roomId,
                    'column_id' => mt_rand(1, 7),
                    'live_status' => LiveEnum::STATUS_CLOSED,
                    'last_live_time' => time(),
                    'fans_count' => mt_rand(1000, 100000),
                ]);
                $live = Live::create([
                    'userid' => $user['id'],
                    'room_id' => $roomId,
                    'room_name' => $nickName,
                    'room_cover' => $user['avatar'],
                    'column_id' => $anchor['column_id'],
                    'is_virtual' => 1,
                    'status' => LiveEnum::STATUS_CLOSED,
                    'push_stream_address' => LiveService::createPushStreamAddress($roomId),
                    'play_stream_address' => LiveService::createPlayAddress($roomId, 'flv'),
                    'play_stream_address2' => LiveService::createPlayAddress($roomId, 'm3u8'),
                    'visit_history' => $anchor['fans_count'] * 5,
                ]);
                if ($user && $anchor && $live) {
                    Db::commit();
                    $succ++;
                } else {
                    Db::rollBack();
                }
            } catch (\Exception $e) {
                Db::rollBack();
            }
        }
        return $this->apiReturn(200, sprintf('成功创建 %d 个虚拟直播间', $succ));
    }

    public function importTestAnchor()
    {
        $http = new Client();
        try {
            $res = $http->post('https://833vip27.app/business/anchor/rank', [
                'body' => '{"type":3}',
                'headers' => [
                    'Content-Type' => 'application/json;charset=UTF-8'
                ],
            ]);
            $result = json_decode((string)$res->getBody(), true);
        } catch (GuzzleException|\Exception $e) {
            echo $e->getMessage();
        }
        if (!empty($result['data'])) {
            foreach ($result['data'] as $r) {
                echo $r['nickName'] . "\n";
                if (str_contains($r['nickName'], '原声直播') || User::query()->where('nickname', $r['nickName'])->exists()) {
                    continue;
                }
                try {
                    Db::beginTransaction();
                    $avatar = syncFile($r['userImage']);
                    $random = create_randomstr(10);
                    $email = $random . '@live.91kuaixiu.com';
                    $user = UserLogic::register([
                        'username' => $random,
                        'nickname' => $r['nickName'],
                        'mobile' => '',
                        'email' => $email,
                        'avatar' => $avatar,
                        'role_id' => UserEnum::USER_TYPE_ANCHOR,
                        'password' => '123456',
                    ]);

                    $roomId = mt_rand(1, 9) . random(7);
                    $anchor = UserModelAnchor::create([
                        'userid' => $user['id'],
                        'room_id' => $roomId,
                        'catid' => mt_rand(1, 7),
                        'live_status' => LiveEnum::STATUS_CLOSED,
                        'last_live_time' => time(),
                        'fans_count' => mt_rand(1000, 1000000),
                    ]);
                    $live = Live::create([
                        'userid' => $user['id'],
                        'room_id' => $roomId,
                        'room_name' => $r['nickName'],
                        'catid' => $anchor['catid'],
                        'status' => LiveEnum::STATUS_CLOSED,
                        'push_stream_address' => LiveService::createPushStreamAddress($roomId),
                        'play_stream_address' => LiveService::createPlayAddress($roomId, 'flv'),
                        'play_stream_address2' => LiveService::createPlayAddress($roomId, 'm3u8'),
                        'visit_history' => $r['visitCount'],
                    ]);
                    if ($user && $anchor && $live) {
                        Db::commit();
                    } else {
                        Db::rollBack();
                        $this->logger->warning("导入失败");
                    }

                } catch (\Exception $e) {
                    Db::rollBack();
                    echo $e->getMessage();
                }
            }
        }
    }

    /**
     * 导入测试专家
     * @return ResponseInterface
     */
    public function testImportExpert(): ResponseInterface
    {
        $succ = 0;
        $api = make(LiveApi::class, ['gateway' => env('TARGET_API_GATEWAY', ''), 'requestDelayTime' => floatval(env('TARGET_API_REQUEST_DELAY', 0))]);
        try {
            $result = $api->getExpertRank(2, 4);
            if (!empty($result['data'])) {
                foreach ($result['data'] as $r) {
                    if (User::query()->where('nickname', $r['expertNickName'])->exists()) {
                        continue;
                    }
                    try {
                        $username = 'u' . create_randomstr(10);
                        $email = $username . '@live.91kuaixiu.com';
                        $user = UserLogic::register([
                            'username' => $username,
                            'nickname' => $r['expertNickName'],
                            'mobile' => '',
                            'email' => $email,
                            'avatar' => $r['expertLogo'],
                            'roleId' => UserEnum::USER_TYPE_EXPERT,
                            'isVirtual' => 1,
                            'password' => md5($username),
                        ]);
                        UserModelExpert::create([
                            'userid' => $user['id'],
                            'expert_id' => 0,
                            'expert_desc' => $r['expertDesc'],
                            'fans_count' => $r['fansCount'],
                            'recent_win_rate' => $r['expertWinRate'],
                            'recent_payback_rate' => $r['expertBackRate'],
                            'recent_red_num' => $r['redNum'],
                        ]);
                        $succ++;
                    } catch (\Exception $e) {
                        echo $e->getMessage();
                    }
                }
            }
        } catch (GuzzleException|\Exception $e) {
            echo $e->getMessage();
        }
        return $this->apiReturn(200, sprintf('成功导入 %d 位测试专家', $succ));
    }

    public function matchLive()
    {
        $this->parseToken();
        $userid = Context::get('userid', 0);
        $data = MatchLogic::getMatchLiveList($userid);
        return $this->apiReturn(200, 'succ', $data);
    }

    private function _downFile($file, $timeout = 10): false|string
    {
        $tmpFile = tempnam(sys_get_temp_dir(), 'dl_');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $file);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_FILE, fopen($tmpFile, 'w'));
        $response = curl_exec($ch);
        curl_close($ch);
        if ($response) {
            return $tmpFile;
        }
        return false;
    }
}
